<template>
  <div class="container">
    <div class="upload">
      <el-form label-width="100px">
        <el-form-item label="视频标题">
          <el-input
            v-model="title"
            type="text"
            placeholder="不填写则默认为视频文件名"
          />
        </el-form-item>
        <el-form-item label="选择视频">
          <div class="file">
            选择文件
            <input id="fileUpload" type="file" @change="fileChange($event)" />
          </div>
        </el-form-item>
        <el-form-item label="状态">
          <span>{{ statusText }}</span>
        </el-form-item>
        <el-form-item label="进度">
          <div class="progress-container">
            <div style="width:100%;height:10px;background:#8cc8ff;">
              <div :style="progressStyle" />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="upload-type">
            <el-button
              type="primary"
              :disabled="uploadDisabled"
              @click="authUpload"
              >开始上传</el-button
            >
            <el-button
              type="primary"
              :disabled="pauseDisabled"
              @click="pauseUpload"
              >暂停</el-button
            >
            <el-button
              type="primary"
              :disabled="resumeDisabled"
              @click="resumeUpload"
              >恢复上传</el-button
            >
            <span class="progress">
              上传进度:
              <i id="auth-progress">{{ authProgress }}</i> %
            </span>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
// import axios from 'axios'
import request from "@/utils/request";
export default {
  data() {
    return {
      timeout: "",
      partSize: "",
      parallel: "",
      retryCount: "",
      retryDuration: "",
      region: "cn-shanghai",
      userId: "1621668104157429", // 这个userid 好像没用
      file: null,
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: "",

      uploadAuth: "",
      uploadAddress: "",
      videoId: "",
      title: "",
      progressStyle: "width:0%;height:10px;background:#ff4949;"
    };
  },

  created: function() {
    this.initUploader();
  },
  methods: {
    // 初始化视频上传工具:osssdk，uploadsdk
    initUploader() {
      const ossSdkId = document.getElementById("ossSdkId");
      if (ossSdkId) {
        this.loadUploadScript();
      } else {
        this.loadOssScript(this.loadUploadScript);
      }
    },

    // 动态加载osssdk
    loadOssScript(callback = function() {}) {
      const script1 = document.createElement("script");
      script1.src =
        "http://og-lib.oss-cn-shenzhen.aliyuncs.com/aliyun-oss-sdk-5.3.1.min.js";
      script1.type = "text/javascript";
      script1.setAttribute("id", "ossSdkId");
      const head = document.getElementsByTagName("head")[0];
      head.appendChild(script1);
      script1.onload = script1.onreadystatechange = function() {
        if (
          !this.readyState ||
          this.readyState === "loaded" ||
          this.readyState === "complete"
        ) {
          console.log("1 it is loaded");
          script1.onload = script1.onreadystatechange = null;
          callback();
        }
      };
    },

    // 动态加载uploadsdk
    loadUploadScript() {
      const _this = this;
      // 如果已经存在，就不再加载
      const uploadSdkId = document.getElementById("uploadSdkId");
      if (uploadSdkId) {
        return;
      }
      const head = document.getElementsByTagName("head")[0];
      const script2 = document.createElement("script");
      script2.src =
        "http://og-lib.oss-cn-shenzhen.aliyuncs.com/aliyun-upload-sdk-1.5.0.min.js";
      script2.type = "text/javascript";
      script2.setAttribute("id", "uploadSdkId");
      head.appendChild(script2);
      script2.onload = script2.onreadystatechange = function() {
        if (
          !this.readyState ||
          this.readyState === "loaded" ||
          this.readyState === "complete"
        ) {
          console.log("2 it is loaded");
          script2.onload = script2.onreadystatechange = null;
          _this.createUploader();
        }
      };
    },

    fileChange(e) {
      this.file = e.target.files[0];
      if (!this.file) {
        alert("请先选择需要上传的文件!");
        return;
      }
      // var Title = this.file.name
      var userData = '{"Vod":{}}';
      if (this.uploader) {
        this.uploader.stopUpload();
        this.authProgress = 0;
        this.statusText = "";
      }
      this.uploader = this.createUploader();
      console.log(userData);
      this.uploader.addFile(this.file, null, null, null, userData);
      this.uploadDisabled = false;
      this.pauseDisabled = true;
      this.resumeDisabled = true;
      if (this.title === "") {
        this.title = this.file.name;
      }
    },
    authUpload() {
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.uploadDisabled = true;
        this.pauseDisabled = false;
      }
    },
    // 暂停上传
    pauseUpload() {
      if (this.uploader !== null) {
        this.uploader.stopUpload();
        this.resumeDisabled = false;
        this.pauseDisabled = true;
      }
    },
    // 恢复上传
    resumeUpload() {
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.resumeDisabled = true;
        this.pauseDisabled = false;
      }
    },
    createUploader(type) {
      const self = this;
      const uploader = new AliyunUpload.Vod({
        timeout: self.timeout || 60000,
        partSize: self.partSize || 1048576,
        parallel: self.parallel || 5,
        retryCount: self.retryCount || 3,
        retryDuration: self.retryDuration || 2,
        region: self.region,
        userId: self.userId,
        // 添加文件成功
        addFileSuccess: function(uploadInfo) {
          self.uploadDisabled = false;
          self.resumeDisabled = false;
          self.statusText = "添加文件成功, 等待上传...";
          console.log("addFileSuccess: " + uploadInfo.file.name);
        },
        // 开始上传
        onUploadstarted: function(uploadInfo) {
          // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
          // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
          // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
          // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
          // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
          // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
          // videoId 很可能是根据 File的信息来判断的，如果以前上传过同样的视频，那么就会有videoId
          console.log("来到这里没有");
          if (!uploadInfo.videoId) {
            console.log("来到这里没有 哈哈哈", request);

            request
              .get("/admin/video/createUploadVideo", {
                params: {
                  title: self.title,
                  fileName: uploadInfo.file.name
                }
              })
              .then(res => {
                res = res.data;

                uploader.setUploadAuthAndAddress(
                  uploadInfo,
                  res.UploadAuth,
                  res.UploadAddress,
                  res.VideoId
                );
                self.statusText = "文件开始上传...";
                console.log(
                  "onUploadStarted:" +
                    uploadInfo.file.name +
                    ", endpoint:" +
                    uploadInfo.endpoint +
                    ", bucket:" +
                    uploadInfo.bucket +
                    ", object:" +
                    uploadInfo.object
                );
              });

            // createUploadVideo(self.title, uploadInfo.file.name).then(res => {

            // });
          } else {
            console.log("那就走这条线喽");
            // 如果videoId有值，根据videoId刷新上传凭证
            // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
           request
              .get("/admin/video/refreshUploadInfo", {
                videoId: uploadInfo.videoId
              })
              .then(res => {
                res = res.data;
                uploader.setUploadAuthAndAddress(
                  uploadInfo,
                  res.UploadAuth,
                  res.UploadAddress,
                  uploadInfo.videoId
                );
              });
            // refreshUploadInfo(uploadInfo.videoId).then(res => {

            // });
          }
          console.log("aaa");
        },
        // 文件上传成功
        onUploadSucceed: function(uploadInfo) {
          console.log(
            "onUploadSucceed: " +
              uploadInfo.file.name +
              ", endpoint:" +
              uploadInfo.endpoint +
              ", bucket:" +
              uploadInfo.bucket +
              ", object:" +
              uploadInfo.object
          );
          self.statusText = "文件上传成功!";
          self.$emit("uploadSuccess", uploadInfo);
        },
        // 文件上传失败
        onUploadFailed: function(uploadInfo, code, message) {
          console.log(
            "onUploadFailed: file:" +
              uploadInfo.file.name +
              ",code:" +
              code +
              ", message:" +
              message
          );
          self.statusText = "文件上传失败!";
        },
        // 取消文件上传
        onUploadCanceled: function(uploadInfo, code, message) {
          console.log(
            "Canceled file: " +
              uploadInfo.file.name +
              ", code: " +
              code +
              ", message:" +
              message
          );
          self.statusText = "文件已暂停上传";
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function(uploadInfo, totalSize, progress) {
          console.log(
            "onUploadProgress:file:" +
              uploadInfo.file.name +
              ", fileSize:" +
              totalSize +
              ", percent:" +
              Math.ceil(progress * 100) +
              "%"
          );
          const progressPercent = Math.ceil(progress * 100);
          self.authProgress = progressPercent;
          self.progressStyle =
            "width:" + progressPercent + "%;height:10px;background:#ff4949;";
          self.statusText = "文件上传中...";
        },
        // 上传凭证超时
        onUploadTokenExpired: async function(uploadInfo) {
          // 这里目前没用到
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          // let refreshUrl =
          //   'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' +
          //   uploadInfo.videoId

          const { data } = request.get("/admin/video/refreshUploadInfo", {
            videoId: uploadInfo.videoId
          });
          // refreshUploadInfo(uploadInfo.videoId).then(res => {
          const uploadAuth = data.UploadAuth;
          uploader.resumeUploadWithAuth(uploadAuth);
          console.log(
            "upload expired and resume upload with uploadauth " + uploadAuth
          );
          self.statusText = "文件超时...";
          // })
        },
        // 全部文件上传结束
        onUploadEnd: function(uploadInfo) {
          console.log("onUploadEnd: uploaded all the files");
          self.statusText = "文件上传完毕";
        }
      });
      return uploader;
    }
  }
};
</script>

<style scoped>
.progress-container {
  height: 32px;
  margin: auto;
  display: flex;
  align-items: center;
}
.file {
  position: relative;
  display: inline-block;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 4px 12px;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
}
.file input {
  position: absolute;
  font-size: 100px;
  right: 0;
  top: 0;
  opacity: 0;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
</style>
